<template>
  <view class="deposits-container">
    <!-- 保证金卡片 -->
    <view class="balance-card">
      <view class="balance-header">
        <view class="balance-icon">🛡️</view>
        <view class="balance-info">
          <text class="balance-label">信用背书</text>
          <text class="balance-tip">随时可退</text>
        </view>
      </view>

      <view class="balance-amount">
        <text class="amount-value">{{ balance.toFixed(2) }}</text>
        <text class="amount-unit">保证金余额（元）</text>
      </view>

      <view class="balance-actions">
        <button class="balance-btn deposit" @click="showDepositModal">
          增加保证金
        </button>
        <button class="balance-btn refund" @click="showRefundModal">
          退还保证金
        </button>
      </view>
    </view>

    <!-- 保证金规则说明 -->
    <view class="rules-card">
      <view class="rules-title">保证金规则说明</view>
      
      <view class="rule-item">
        <text class="rule-title">保证金的意义：</text>
        <text class="rule-content">1、跟其它同行产生差异化，体现您的信用接单实力；</text>
        <text class="rule-content">2、让用户选择更简单，也更有保障。</text>
      </view>

      <view class="rule-item">
        <text class="rule-title">保证金的赔付原则：</text>
        <text class="rule-content">1、原则上平台希望双方友好协商私下处理；</text>
        <text class="rule-content">2、申请赔付需用户举证，平台依据事实公平受理。</text>
      </view>

      <view class="rule-item">
        <text class="rule-title">保证金的退还：</text>
        <text class="rule-content">广告展示到期后，可随时申请退还。</text>
      </view>
    </view>

    <!-- 充值弹窗 -->
    <view v-if="showDeposit" class="modal-overlay" @click="closeDepositModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">增加保证金</text>
          <text class="modal-close" @click="closeDepositModal">×</text>
        </view>
        
        <view class="modal-body">
          <view class="input-group">
            <text class="input-label">充值金额</text>
            <input 
              v-model="depositAmount"
              class="amount-input"
              type="digit"
              placeholder="请输入充值金额"
            />
          </view>
          
          <view class="amount-tips">
            <view 
              v-for="tip in depositTips"
              :key="tip"
              class="tip-item"
              @click="setDepositAmount(tip)"
            >
              <text>{{ tip }}元</text>
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <button 
            class="modal-btn primary"
            :disabled="!depositAmount || depositAmount <= 0 || depositing"
            @click="handleDeposit"
          >
            {{ depositing ? '处理中...' : '立即充值' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 退款弹窗 -->
    <view v-if="showRefund" class="modal-overlay" @click="closeRefundModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">退还保证金</text>
          <text class="modal-close" @click="closeRefundModal">×</text>
        </view>
        
        <view class="modal-body">
          <view class="input-group">
            <text class="input-label">退款金额</text>
            <input 
              v-model="refundAmount"
              class="amount-input"
              type="digit"
              placeholder="请输入退款金额"
              :max="balance"
            />
            <text class="balance-tip">可退余额：{{ balance.toFixed(2) }}元</text>
          </view>
          
          <view class="input-group">
            <text class="input-label">退款原因</text>
            <textarea 
              v-model="refundReason"
              class="reason-textarea"
              placeholder="请填写详细的退款原因（至少5个字符）"
              maxlength="200"
            />
            <text class="char-count">{{ refundReason.length }}/200</text>
          </view>
        </view>

        <view class="modal-footer">
          <button 
            class="modal-btn primary"
            :disabled="!canRefund || refunding"
            @click="handleRefund"
          >
            {{ refunding ? '提交中...' : '提交申请' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-content">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { serviceDepositAPI } from '@/utils/api.js'

// 响应式数据
const balance = ref(0)
const loading = ref(false)
const showDeposit = ref(false)
const showRefund = ref(false)
const depositAmount = ref('')
const refundAmount = ref('')
const refundReason = ref('')
const depositing = ref(false)
const refunding = ref(false)

// 充值金额建议
const depositTips = [100, 200, 500, 1000]

// 计算属性
const canRefund = computed(() => {
  return refundAmount.value && 
         Number(refundAmount.value) > 0 && 
         Number(refundAmount.value) <= balance.value &&
         refundReason.value.trim().length >= 5
})

// 生命周期
onMounted(() => {
  loadBalance()
})

// 方法定义
/**
 * 加载保证金余额
 */
const loadBalance = async () => {
  try {
    loading.value = true
    const result = await serviceDepositAPI.getBalance()
    
    if (result.success) {
      balance.value = result.data.balance || 0
    } else {
      uni.showToast({
        title: result.message || '加载余额失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载保证金余额失败:', error)
    uni.showToast({
      title: '加载余额失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 显示充值弹窗
 */
const showDepositModal = () => {
  showDeposit.value = true
  depositAmount.value = ''
}

/**
 * 关闭充值弹窗
 */
const closeDepositModal = () => {
  showDeposit.value = false
  depositAmount.value = ''
}

/**
 * 设置充值金额
 */
const setDepositAmount = (amount) => {
  depositAmount.value = amount.toString()
}

/**
 * 处理充值
 */
const handleDeposit = async () => {
  const amount = Number(depositAmount.value)
  
  if (!amount || amount <= 0) {
    uni.showToast({
      title: '请输入有效金额',
      icon: 'none'
    })
    return
  }

  if (amount < 10) {
    uni.showToast({
      title: '最小充值金额为10元',
      icon: 'none'
    })
    return
  }

  try {
    depositing.value = true
    
    const result = await serviceDepositAPI.deposit({ amount })
    
    if (result.success) {
      const { deposit, payment_params } = result.data
      
      // 处理支付
      if (payment_params.mockMode) {
        // 模拟支付
        uni.showModal({
          title: '模拟支付',
          content: `充值金额：${amount}元\n点击确定完成支付`,
          success: async (res) => {
            if (res.confirm) {
              await handleMockPayment(payment_params.orderNumber)
            }
          }
        })
      } else {
        // 真实微信支付
        try {
          await wx.requestPayment({
            timeStamp: payment_params.timeStamp,
            nonceStr: payment_params.nonceStr,
            package: payment_params.package,
            signType: payment_params.signType,
            paySign: payment_params.paySign,
            success: () => {
              uni.showToast({
                title: '充值成功',
                icon: 'success'
              })
              closeDepositModal()
              loadBalance()
            },
            fail: (err) => {
              if (!err.errMsg.includes('cancel')) {
                uni.showToast({
                  title: '支付失败',
                  icon: 'none'
                })
              }
            }
          })
        } catch (payError) {
          console.error('调用微信支付失败:', payError)
          uni.showToast({
            title: '支付调用失败',
            icon: 'none'
          })
        }
      }
    } else {
      uni.showToast({
        title: result.message || '创建充值订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('充值失败:', error)
    uni.showToast({
      title: '充值失败',
      icon: 'none'
    })
  } finally {
    depositing.value = false
  }
}

/**
 * 处理模拟支付
 */
const handleMockPayment = async (orderNumber) => {
  try {
    const result = await serviceDepositAPI.mockPaymentSuccess({ order_number: orderNumber })
    
    if (result.success) {
      uni.showToast({
        title: '充值成功',
        icon: 'success'
      })
      closeDepositModal()
      loadBalance()
    } else {
      uni.showToast({
        title: '模拟支付失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('模拟支付失败:', error)
    uni.showToast({
      title: '模拟支付失败',
      icon: 'none'
    })
  }
}

/**
 * 显示退款弹窗
 */
const showRefundModal = () => {
  if (balance.value <= 0) {
    uni.showToast({
      title: '暂无可退金额',
      icon: 'none'
    })
    return
  }
  
  showRefund.value = true
  refundAmount.value = ''
  refundReason.value = ''
}

/**
 * 关闭退款弹窗
 */
const closeRefundModal = () => {
  showRefund.value = false
  refundAmount.value = ''
  refundReason.value = ''
}

/**
 * 处理退款
 */
const handleRefund = async () => {
  const amount = Number(refundAmount.value)
  
  if (!amount || amount <= 0) {
    uni.showToast({
      title: '请输入有效金额',
      icon: 'none'
    })
    return
  }

  if (amount > balance.value) {
    uni.showToast({
      title: '退款金额不能超过余额',
      icon: 'none'
    })
    return
  }

  if (refundReason.value.trim().length < 5) {
    uni.showToast({
      title: '请填写详细的退款原因',
      icon: 'none'
    })
    return
  }

  try {
    refunding.value = true
    
    const result = await serviceDepositAPI.refund({
      amount,
      refund_reason: refundReason.value.trim()
    })
    
    if (result.success) {
      uni.showToast({
        title: '退款申请已提交',
        icon: 'success'
      })
      closeRefundModal()
      loadBalance()
    } else {
      uni.showToast({
        title: result.message || '提交退款申请失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提交退款申请失败:', error)
    uni.showToast({
      title: '提交申请失败',
      icon: 'none'
    })
  } finally {
    refunding.value = false
  }
}

</script>

<style scoped>
.deposits-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.balance-card {
  background: linear-gradient(135deg, #22c55e, #16a34a);
  margin: 30rpx;
  border-radius: 20rpx;
  padding: 40rpx;
  color: white;
  box-shadow: 0 8rpx 24rpx rgba(34, 197, 94, 0.3);
}

.balance-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.balance-icon {
  font-size: 48rpx;
  margin-right: 20rpx;
}

.balance-info {
  display: flex;
  flex-direction: column;
}

.balance-label {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 8rpx;
}

.balance-tip {
  font-size: 24rpx;
  opacity: 0.8;
}

.balance-amount {
  text-align: center;
  margin-bottom: 40rpx;
}

.amount-value {
  display: block;
  font-size: 72rpx;
  font-weight: 700;
  line-height: 1;
  margin-bottom: 16rpx;
}

.amount-unit {
  font-size: 28rpx;
  opacity: 0.9;
}

.balance-actions {
  display: flex;
  gap: 20rpx;
}

.balance-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 28rpx;
  font-weight: 600;
  border: none;
}

.balance-btn.deposit {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2rpx solid rgba(255, 255, 255, 0.3);
}

.balance-btn.refund {
  background-color: rgba(255, 255, 255, 0.9);
  color: #16a34a;
}

.balance-btn:active {
  opacity: 0.8;
}

.rules-card {
  background-color: #ffffff;
  margin: 0 30rpx 30rpx;
  border-radius: 12rpx;
  padding: 30rpx;
}

.rules-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 30rpx;
}

.rule-item {
  margin-bottom: 30rpx;
}

.rule-item:last-child {
  margin-bottom: 0;
}

.rule-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 12rpx;
}

.rule-content {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  display: block;
  margin-bottom: 8rpx;
}

.rule-content:last-child {
  margin-bottom: 0;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: #ffffff;
  border-radius: 20rpx;
  width: 85%;
  max-width: 600rpx;
  max-height: 70vh;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.modal-close {
  font-size: 40rpx;
  color: #999;
  line-height: 1;
}

.modal-body {
  padding: 30rpx;
}

.input-group {
  margin-bottom: 30rpx;
}

.input-group:last-child {
  margin-bottom: 0;
}

.input-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  display: block;
  margin-bottom: 16rpx;
}

.amount-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 32rpx;
  color: #333;
  box-sizing: border-box;
}

.amount-input:focus {
  border-color: #22c55e;
}

.reason-textarea {
  width: 100%;
  min-height: 120rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  resize: none;
}

.reason-textarea:focus {
  border-color: #22c55e;
}

.balance-tip,
.char-count {
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
  display: block;
}

.amount-tips {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.tip-item {
  padding: 16rpx 24rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #666;
  background-color: #f8f9fa;
}

.tip-item:active {
  background-color: #22c55e;
  color: white;
  border-color: #22c55e;
}

.modal-footer {
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #e5e5e5;
}

.modal-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
}

.modal-btn.primary {
  background-color: #22c55e;
  color: white;
}

.modal-btn.primary:disabled {
  background-color: #cccccc;
  color: #999999;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
}

.loading-text {
  font-size: 28rpx;
}
</style>